import {load, Store as TauriStore} from "@tauri-apps/plugin-store";

export class Store {

  private static stores = new Map<string, Promise<TauriStore>>();
  private readonly store: Promise<TauriStore>;

  constructor(storeName: string) {
    this.store = Store.getStore(storeName);
  }

  private static async getStore(name: string): Promise<TauriStore> {
    if (!name) {
      name = 'app';
    }
    if (this.stores.has(name)) {
      return this.stores.get(name)!;
    }
    const store = load(`${name}.json`, {autoSave: true});
    this.stores.set(name, store);
    return store;
  }

  async get<T>(key: string, defaultValue?: T, storeName?: string): Promise<T> {
    const store = await this.store;
    const value = await store.get(key);
    if (value === undefined) {
      return defaultValue as T;
    }
    return value as T;
  }

  async set<T>(key: string, value: T, storeName?: string): Promise<void> {
    const store = await this.store;
    await store.set(key, value);
  }

  async delete(key: string, storeName?: string): Promise<void> {
    const store = await this.store;
    await store.delete(key);
  }

  async clear(storeName?: string): Promise<void> {
    await(await this.store).clear();
  }
}